import { reqGetShopCartInfo,reqDeteletCartById,reqUpdateCheckById } from "@/api"
import { get, result } from "lodash"

const state={
  shopCartList:[],
 
}
const actions={
  async getShopCartList(context){
      let result  =  await reqGetShopCartInfo()

      if(result.code==200){
        
        context.commit('GETSHOPCARTLIST',result.data)
      }
  },
  async deleteCartById(context,skuId){
    let result= await reqDeteletCartById(skuId);
    if(result.code==200){
      return 'ok'
    }
    else{
      return Promise.reject(new error('failed'))
    }
   },
   async updateCheckById(context,{skuId,isChecked}){
    
    
    let result =await reqUpdateCheckById(skuId,isChecked);

    if(result.code==200){
  
      return 'ok'
    }
    else{
      
      return Promise.reject(new error('failed'))
    }
    
  },
   deleteAllCheckCart({dispatch,getters}){
     let PromiseAll=[];
     getters.shopCartList.cartInfoList.forEach(element => {
      /* console.log('仓库',element.isChecked) */
      
        let result=  element.isChecked==1? dispatch('deleteCartById',element.skuId):''
         
          //将每次的Promise返回到数组中
            PromiseAll.push(result)
        
       
     });
       //只要全部的p1||p1..都成功为成功，否则为失败
     return Promise.all(PromiseAll)
  } ,
  deselectCheckAll({dispatch,getters},isAllCheck){
    
    let promiseAll=[]
    getters.shopCartList.cartInfoList.forEach((element)=>{
      
      if(isAllCheck){
     let result= dispatch('updateCheckById',{skuId:element.skuId,isChecked:1})
      }
      else{
        let result=  dispatch('updateCheckById',{skuId:element.skuId,isChecked:0})
      }

      promiseAll.push(result)
        
    })

    return Promise.all(promiseAll)
  }
}
const mutations={
  GETSHOPCARTLIST(state,shopCartList){
    state.shopCartList=shopCartList
   
  },


}

const getters={
  shopCartList(state){
  return state.shopCartList[0]  || []
  }

}

export default {
  state,
  actions,
  mutations,
  getters
}